var rs485 = require("rs485");
var adc = require("adc");
var gpio = require("gpio");
var math = require("math");
var watchdog = require("watchdog");

//初始化adc，选择PC0作为采样端口
//init支持的采样通道为0 ~ 3：
//0 ----- PC0
//1 ----- PC1
//2 ----- PC2
//3 ----- PC3
adc.init(0);

//parity为字符串：none, odd, even
rs485.init(9600, 8, 1, "none");

gpio.init("PORTC", 6, 1);
gpio.init("PORTC", 7, 0);
gpio.init("PORTC", 8, 0);

gpio.write("PORTC", 6, 1);

function getTemp(volt, res, vr)
{
	var G = 100/res + 1;
	var R = 240;
	var VR = vr/(240+vr)*3;
	var V = volt;
	var T = (V*R + G*VR*R)/(3*G - V - G*VR) -100;
	T = T*2.50;
	return T;
}

function writeLcdCmd(cmd){
	rs485.write(cmd);
	rs485.write(255);
	rs485.write(255);
	rs485.write(255);
}

writeLcdCmd("t4.txt=\"6\"");

//采样的回调函数
function sample()
{	
	var flag = false;
	watchdog.feed();
	print("feed");
	var T1 = getTemp(adc.read(0), 40.3, 82.6);
	var T2 = getTemp(adc.read(1), 40.3, 82.2);
	
	T1 = math.round(T1);
	T2 = math.round(T2);
	
	writeLcdCmd("t2.txt=\"" + parseInt(T1) + "\"");
	writeLcdCmd("t3.txt=\"" + parseInt(T2) + "\"");
	
	var F1 = gpio.read("PORTC", 7);
	var F2 = gpio.read("PORTC", 8);
	
	if(F1 == 1){
		writeLcdCmd("t0.txt=\"Left Stop\"");
		writeLcdCmd("tm0.en=0");
		flag = true;
	}
	else{
		writeLcdCmd("t0.txt=\"Left Run\"");
		writeLcdCmd("tm0.en=1");
	}
	
	if(F2 == 1){
		writeLcdCmd("t1.txt=\"Right Stop\"");
		writeLcdCmd("tm1.en=0");
		flag = true;
	}
	else{
		writeLcdCmd("t1.txt=\"Right Run\"");
		writeLcdCmd("tm1.en=1");
	}
	
	if(T2 > 90)
		flag = true;
	else{
		if(T2 > 60){
			if(T1 - T2 < 6)
				flag = true;
		}
	}
	
	if(flag)
	{
		writeLcdCmd("t8.txt=\"Warning!\"");
		gpio.write("PORTC", 6, 0);
	}
	else
	{
		writeLcdCmd("t8.txt=\"OK\"");
		gpio.write("PORTC", 6, 1);
	}
}
//设置debug函数调用周期为1000ms
setInterval(sample, 1000);

//485回调函数，打印数据和大小
function read_callback(size){
	print(size);
}
//注册485读取函数
rs485.on(read_callback);

watchdog.init(5000);

function loop(){
	while(true){

	}
}

loop();
